const express = require('express')
const cors = require('cors')
const fs = require('fs')
const path = require('path')

// 读取配置文件
const configPath = path.join(__dirname, 'analytics-config.json')
let config = {}

try {
    if (fs.existsSync(configPath)) {
        config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
        console.log('✅ 已加载配置文件')
        
        // 动态获取服务器地址
        const os = require('os')
        const networkInterfaces = os.networkInterfaces()
        let serverIP = 'localhost'
        
        // 尝试获取服务器IP
        for (const name of Object.keys(networkInterfaces)) {
            for (const interface of networkInterfaces[name]) {
                if (interface.family === 'IPv4' && !interface.internal) {
                    serverIP = interface.address
                    break
                }
            }
            if (serverIP !== 'localhost') break
        }
        
        // 如果配置中有占位符，替换为实际IP
        if (config.analytics.baseUrl.includes('{SERVER_IP}')) {
            config.analytics.baseUrl = config.analytics.baseUrl.replace('{SERVER_IP}', serverIP)
            console.log(`🔄 已设置服务器地址: ${config.analytics.baseUrl}`)
        }
    } else {
        console.log('⚠️  配置文件不存在，使用默认配置')
        config = {
            server: { port: 3001, host: '0.0.0.0' },
            analytics: { baseUrl: 'http://localhost:3001' }
        }
    }
} catch (error) {
    console.error('❌ 读取配置文件失败:', error)
    config = {
        server: { port: 3001, host: '0.0.0.0' },
        analytics: { baseUrl: 'http://localhost:3001' }
    }
}

const app = express()
const PORT = config.server.port
const DATA_FILE = path.join(__dirname, 'analytics-data.json')

// 中间件
// 使用更宽松的 CORS 配置来解决跨域问题
app.use(cors({
    origin: function (origin, callback) {
        // 允许所有来源，包括没有 origin 的请求（如移动端应用）
        callback(null, true)
    },
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Referer', 'User-Agent'],
    exposedHeaders: ['Content-Length', 'X-Requested-With'],
    maxAge: 86400
}))

// 添加 Referrer Policy 头
app.use((req, res, next) => {
    res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade')
    next()
})

app.use(express.json())

// 确保数据文件存在
function ensureDataFile() {
  if (!fs.existsSync(DATA_FILE)) {
    const initialData = {
      versions: {
        latest: {
          stats: {
            totalVisits: 0,
            todayVisits: 0,
            weekVisits: 0,
            monthVisits: 0
          },
          popularPages: [],
          lastUpdated: new Date().toISOString(),
          todayDate: new Date().toDateString(),
          weekDate: getWeekOfYear(new Date()),
          monthDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
        }
      }
    }
    fs.writeFileSync(DATA_FILE, JSON.stringify(initialData, null, 2))
    console.log(`✅ 创建初始数据文件: ${DATA_FILE}`)
  }
}

// 读取数据
function readData() {
  try {
    const data = fs.readFileSync(DATA_FILE, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    console.error('读取数据文件失败:', error)
    return {
      versions: {
        latest: {
          stats: {
            totalVisits: 0,
            todayVisits: 0,
            weekVisits: 0,
            monthVisits: 0
          },
          popularPages: [],
          lastUpdated: new Date().toISOString()
        }
      }
    }
  }
}

// 写入数据
function writeData(data) {
  try {
    fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2))
    return true
  } catch (error) {
    console.error('写入数据文件失败:', error)
    return false
  }
}

// 更新页面访问统计
function updatePageViews(pageData, version = 'latest') {
  const data = readData()
  
  // 确保版本数据存在
  if (!data.versions) {
    data.versions = {}
  }
  if (!data.versions[version]) {
    data.versions[version] = {
      stats: {
        totalVisits: 0,
        todayVisits: 0,
        weekVisits: 0,
        monthVisits: 0
      },
      popularPages: [],
      lastUpdated: new Date().toISOString(),
      todayDate: new Date().toDateString(),
      weekDate: getWeekOfYear(new Date()),
      monthDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
    }
  }
  
  const versionData = data.versions[version]
  
  // 查找是否已存在该页面
  const existingPageIndex = versionData.popularPages.findIndex(page => page.path === pageData.path)
  
  if (existingPageIndex !== -1) {
    // 更新现有页面访问次数
    versionData.popularPages[existingPageIndex].views++
  } else {
    // 添加新页面
    versionData.popularPages.push({
      path: pageData.path,
      title: pageData.title || pageData.path,
      views: 1
    })
  }
  
  // 按访问次数排序
  versionData.popularPages.sort((a, b) => b.views - a.views)
  
  // 保留前1500个热门页面
  versionData.popularPages = versionData.popularPages.slice(0, 1500)
  
  // 更新统计数据
  versionData.stats.totalVisits++
  
  // 更新今日访问量（基于日期）
  const today = new Date().toDateString()
  if (!versionData.todayDate || versionData.todayDate !== today) {
    versionData.stats.todayVisits = 1
    versionData.todayDate = today
  } else {
    versionData.stats.todayVisits++
  }
  
  // 更新本周访问量（基于周）
  const currentWeek = getWeekOfYear(new Date())
  if (!versionData.weekDate || versionData.weekDate !== currentWeek) {
    versionData.stats.weekVisits = 1
    versionData.weekDate = currentWeek
  } else {
    versionData.stats.weekVisits++
  }
  
  // 更新本月访问量（基于月）
  const currentMonth = new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
  if (!versionData.monthDate || versionData.monthDate !== currentMonth) {
    versionData.stats.monthVisits = 1
    versionData.monthDate = currentMonth
  } else {
    versionData.stats.monthVisits++
  }
  
  versionData.lastUpdated = new Date().toISOString()
  
  return writeData(data)
}

// 获取周数
function getWeekOfYear(date) {
  const firstDayOfYear = new Date(date.getFullYear(), 0, 1)
  const pastDaysOfYear = (date - firstDayOfYear) / 86400000
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7)
}

// API 路由

// 获取统计数据
app.get('/api/stats', (req, res) => {
  try {
    const { version = 'latest' } = req.query
    const data = readData()
    
    // 确保版本数据存在
    if (!data.versions || !data.versions[version]) {
      return res.json({
        success: true,
        data: {
          stats: {
            totalVisits: 0,
            todayVisits: 0,
            weekVisits: 0,
            monthVisits: 0
          },
          popularPages: [],
          lastUpdated: new Date().toISOString()
        }
      })
    }
    
    const versionData = data.versions[version]
    res.json({
      success: true,
      data: {
        stats: versionData.stats,
        popularPages: versionData.popularPages,
        lastUpdated: versionData.lastUpdated
      }
    })
  } catch (error) {
    console.error('获取统计数据失败:', error)
    res.status(500).json({
      success: false,
      error: '获取统计数据失败'
    })
  }
})

// 检查是否为404页面
function is404Page(pageData) {
  const { path, title } = pageData
  
  // 检查页面标题是否包含404相关关键词
  const title404Keywords = ['404', 'not found', '页面未找到', '页面不存在']
  const has404Title = title404Keywords.some(keyword => 
    title && title.toLowerCase().includes(keyword.toLowerCase())
  )
  
  // 检查路径是否为特定的404页面路径（精确匹配）
  const errorPaths = ['/404',  '/not-found', '/404.html']
  const isErrorPath = errorPaths.some(errorPath => 
    path && path.toLowerCase() === errorPath.toLowerCase()
  )
  
  // 检查路径是否以 /404 开头（404页面）
  const is404Path = path && path.toLowerCase().startsWith('/404')
  
  return has404Title || isErrorPath || is404Path
}

// 记录页面访问
app.post('/api/pageview', (req, res) => {
  try {
    console.log('📊 收到页面访问请求:', req.body)

    const { pageData, version = 'latest' } = req.body
    
    if (!pageData || !pageData.path) {
      console.error('❌ 请求数据格式错误:', req.body)
      return res.status(400).json({
        success: false,
        error: '缺少页面数据或页面路径',
        received: req.body
      })
    }

    // 检查是否为404页面
    if (is404Page(pageData)) {
      console.log('🚫 跳过404页面访问记录:', pageData.path)
      return res.json({
        success: true,
        message: '404页面已跳过记录',
        version: version
      })
    }

    // 确保 pageData 有必要的字段
    const validPageData = {
      path: pageData.path,
      title: pageData.title || pageData.path
    }

    // 更新页面访问统计
    if (updatePageViews(validPageData, version)) {
      res.json({
        success: true,
        message: '页面访问记录成功',
        version: version
      })
    } else {
      res.status(500).json({
        success: false,
        error: '记录页面访问失败'
      })
    }
  } catch (error) {
    console.error('记录页面访问失败:', error)
    res.status(500).json({
      success: false,
      error: '记录页面访问失败',
      details: error.message
    })
  }
})

// 获取原始数据
app.get('/api/data', (req, res) => {
  try {
    const data = readData()
    res.json({
      success: true,
      data
    })
  } catch (error) {
    console.error('获取原始数据失败:', error)
    res.status(500).json({
      success: false,
      error: '获取原始数据失败'
    })
  }
})

// 清除所有数据
app.delete('/api/data', (req, res) => {
  try {
    const { version } = req.query
    
    if (version) {
      // 清除指定版本的数据
      const data = readData()
      if (data.versions && data.versions[version]) {
        data.versions[version] = {
          stats: {
            totalVisits: 0,
            todayVisits: 0,
            weekVisits: 0,
            monthVisits: 0
          },
          popularPages: [],
          lastUpdated: new Date().toISOString(),
          todayDate: new Date().toDateString(),
          weekDate: getWeekOfYear(new Date()),
          monthDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
        }
        
        if (writeData(data)) {
          res.json({
            success: true,
            message: `版本 ${version} 数据清除成功`
          })
        } else {
          res.status(500).json({
            success: false,
            error: '清除数据失败'
          })
        }
      } else {
        res.status(404).json({
          success: false,
          error: `版本 ${version} 不存在`
        })
      }
    } else {
      // 清除所有数据
      const initialData = {
        versions: {
          latest: {
            stats: {
              totalVisits: 0,
              todayVisits: 0,
              weekVisits: 0,
              monthVisits: 0
            },
            popularPages: [],
            lastUpdated: new Date().toISOString(),
            todayDate: new Date().toDateString(),
            weekDate: getWeekOfYear(new Date()),
            monthDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
          }
        }
      }
      
      if (writeData(initialData)) {
        res.json({
          success: true,
          message: '所有数据清除成功'
        })
      } else {
        res.status(500).json({
          success: false,
          error: '清除数据失败'
        })
      }
    }
  } catch (error) {
    console.error('清除数据失败:', error)
    res.status(500).json({
      success: false,
      error: '清除数据失败'
    })
  }
})

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: '统计服务运行正常',
    timestamp: new Date().toISOString(),
    dataFile: DATA_FILE
  })
})

// 启动服务器
function startServer() {
  ensureDataFile()
  
  app.listen(PORT, config.server.host, () => {
    console.log(`📊 统计服务已启动`)
    console.log(`📍 服务地址: ${config.analytics.baseUrl}`)
    console.log(`📁 数据文件: ${DATA_FILE}`)
    console.log(`🔧 配置信息:`)
    console.log(`   - 端口: ${config.server.port}`)
    console.log(`   - 主机: ${config.server.host}`)
    console.log(`   - API前缀: ${config.analytics.apiPrefix}`)
    console.log(`   - CORS: ${config.analytics.enableCors ? '启用' : '禁用'}`)
    console.log(`🔗 API 文档:`)
    console.log(`   GET  ${config.analytics.apiPrefix}/stats     - 获取统计数据`)
    console.log(`   POST ${config.analytics.apiPrefix}/pageview  - 记录页面访问`)
    console.log(`   GET  ${config.analytics.apiPrefix}/data      - 获取原始数据`)
    console.log(`   DELETE ${config.analytics.apiPrefix}/data    - 清除所有数据`)
    console.log(`   GET  ${config.analytics.apiPrefix}/health    - 健康检查`)
  })
}

// 如果直接运行此文件，启动服务器
if (require.main === module) {
  startServer()
}

module.exports = { app, startServer, readData, writeData } 